import json
import os
import sys
import socket

from nameko.rpc import rpc

sys.path.append("../")

from utils import dbutil,Utils
from config import Config

class Inference:
    name = "ext_summary"
    @rpc
    def get_summary(self,user_id, model_name,query,src):
        # 获取模型路径
        sql = """
                select status,model_path from app_model
                where user_id='{}' and model_name='{}'
        """.format(user_id,model_name)
        data = dbutil.query(sql)
        if data:
            status = data[0][0]
            if status == 'finish':
                model_path = os.path.join(data[0][1], model_name + '.pt')
                # 连接服务器
                client = socket.socket()
                addr = ('127.0.0.1', 12345)
                client.connect(addr)
                data = {
                    'task': 'ext',
                    'mode': 'test_text',
                    'have_query': 'T',
                    'language': 'Chinese',
                    'test_from': model_path,
                    'query': query,
                    'src': src
                }
                data = json.dumps(data)
                # 发送数据
                client.sendall(data.encode('utf-8'))
                # 接受服务器返回结果
                result = client.recv(1024).decode()
                client.close()
                print(result)
                result = {
                    'summary': result,
                    'status': 200
                }
            else:
                result = {
                    'msg': "模型未训练或训练未完成",
                    'status': 403
                }
        else:
            result = {
                'msg': "模型不存在",
                'status': 404
            }
        return json.dumps(result)


